package v1

import (
	"fmt"
	"gin-project/middleware"
	"gin-project/model"
	"gin-project/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func AdminLogin(ctx *gin.Context) {
	username := ctx.PostForm("name")
	passwrod := ctx.PostForm("password")

	token, code := model.AdminLogin(username, passwrod)
	fmt.Println(token)
	fmt.Println(code)
	ctx.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": errmsg.GetErrMsg(code),
		"token": token,
	})
	return
}

func AdminAuth() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		token := ctx.Request.Header.Get("Authorization")
		fmt.Println("==================")
		fmt.Println(token)
		if token == "" {
			ctx.JSON(http.StatusOK, gin.H{
				"code": errmsg.TOKEN_GET_FAILED,
				"msg": errmsg.GetErrMsg(errmsg.TOKEN_GET_FAILED),
			})
			ctx.Abort()
			return
		}
		
		_, code := middleware.AuthToken(strings.Split(token, " ")[1])
		if code != errmsg.SUCCESS {
			ctx.JSON(http.StatusOK, gin.H{
				"code": errmsg.TOKEN_PARSE_FAILED,
				"msg": errmsg.GetErrMsg(errmsg.TOKEN_PARSE_FAILED),
			})
			ctx.Abort()
			return
		}

		ctx.Next()
	}
}
